package com.xialuo.shiro;


import cn.hutool.json.JSONNull;
import cn.hutool.json.JSONUtil;
import com.xialuo.common.lang.Result;
import com.xialuo.logic.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtFilter extends AuthenticatingFilter {


    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String authorization = request.getHeader("Authorization");

        if(authorization==null){

            return null;
        }

        return new JwtToken(authorization);

    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String jwtToken = request.getHeader("Authorization");

        if(StringUtils.isEmpty(jwtToken))
        {
            return true;
        }else{


            //校验jwtToken
            Claims claims = JwtUtils.getClaim(jwtToken);
            if(claims==null || JwtUtils.isExpired(jwtToken))
            {
               throw new RuntimeException("token过期失效！");

            }

            //登录处理
             return  executeLogin(servletRequest,servletResponse);

        }


    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {

        HttpServletResponse resp = (HttpServletResponse) response;
        Throwable throwable = e.getCause() == null ? e : e.getCause();

        Result fail = Result.fail(throwable.getMessage());

        String result = JSONUtil.toJsonStr(fail);

        try {
            resp.getWriter().println(result);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return false;
    }

}
